
package gml.android.osc;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import gml.android.osc.Connection;

/**
 * Class modified from this source: 
 * http://stackoverflow.com/questions/3325915/android-activity-establish-network-connection
 * 
 * {@link NetworkConnection}: Verify if what type of Connection is (provided by {@link Context.CONNECTIVITY_SERVICE}) 
 * and {@link NetworkInfo});
 * 
 * {@link Log} is active by default
 * 
 * Also, you will have to add this permission to your AndroidManifest.xml file: <b>
 * uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" </b>
 * 
 * @see {@link http://stackoverflow.com/questions/3325915/android-activity-establish-network-connection}
 * @see {@link ConnectivityManager}
 * @see {@link NetworkInfo}
 * @see {@link OSCConnection}
 * @version 0.1
 * @author gcravista.gmail.dot.com
 *
 */
public class NetworkConnection implements Connection {

	private static boolean connected;

	/** verify if device has an Network connection in specific {@link Context}
	 * @see {@link ConnectivityManager}, {@link NetworkInfo}, {@link COntext.CONNECTIVITY_SERVICE}  */
	@SuppressWarnings("null")
	public static Boolean isOnline(Context context) {
		try {
			Log.i(TAG, "Starting ConnectivityManager. Wait...");
			ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (cm != null) {
				NetworkInfo info = cm.getActiveNetworkInfo();
			    connected = info.isConnectedOrConnecting();
				if (connected) {
					Log.d(TAG, "Network State: "+info.getDetailedState());
					Log.d(TAG, "Connection type: "+info.getExtraInfo());
					Log.d(TAG, "Subtype connection: "+info.getTypeName());
					return true;
				}
			} else {
				Log.e(TAG, "Not connected: ");
				Log.e(TAG,"	"+cm.getAllNetworkInfo().toString());
				return false;
			}
		}
		catch (Exception e) {
			Log.e(TAG, "Could not connect", e);
			return false;
		}
		return connected;
    }

	@Override
	public Boolean isConnected() {
		return connected;
	}

}
